package com.hongguowei.lambda;

import com.hongguowei.entity.Author;
import com.hongguowei.entity.Book;

import javax.xml.transform.Source;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class OptionalTest {
    public static void main(String[] args) {
        Author author1 = getAuthor();
        Optional<Author> objectOptional = Optional.ofNullable(author1);

        objectOptional.ifPresent(author2 -> System.out.println(author1.getName()));

        objectOptional.orElseGet(Author::new);

        try {
            Author author = objectOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("数据为null"));
            System.out.println(author);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
    private static Author getAuthor(){
        Author author = new Author(1, "张三", 12,null);
        return  author;
    }
    private static  void testFilter(){
        Author author = getAuthor();
        Optional<Author> authorOptional = Optional.ofNullable(author);
        authorOptional.filter(author1 -> author1.getAge() > 100)
                .ifPresent(author12 -> System.out.println(author12.getName()));
    }
    private static  void testMap(){
        Author author = getAuthor();
        Optional<Author> authorOptional = Optional.ofNullable(author);
        if(authorOptional.isPresent()){
            System.out.println(authorOptional.get().getName());
        }
        Optional<List<Book>> optionalBooks = authorOptional.map(Author::getBooks);
        optionalBooks.ifPresent(books -> System.out.println(books));
    }
}
